package com.jeesite.common.utils;

import com.jeesite.common.bean.exception.ActivityUserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 封装一些网络访问方法--->非共用
 * @author ReStartLin
 */
public class HttpUtil {
    public static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    /**
     * 获得微信用户的openid
     * @param appid appid
     * @param secret secret
     * @param code code
     * @return openid
     */
    public static String wx_getOpenId2Json(String appid, String secret, String code) throws ActivityUserException {
        try {//避免与jeesite的异常捕获发生冲突  抛出自定义异常
            //发起http请求
            logger.info("wx code:{}", code);
            String baseUrl = "https://api.weixin.qq.com/sns/jscode2session?";
            baseUrl += "appid=" + appid
                    + "&secret=" + secret
                    + "&js_code=" + code
                    + "&grant_type=authorization_code";
            logger.info("wx baseUrl:{}", baseUrl);
            URL url = new URL(baseUrl);
            BufferedReader reader = null;
            HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(1000);
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            StringBuilder body = new StringBuilder();
            if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                String temp;
                while ((temp = reader.readLine()) != null) {
                    body.append(temp);
                }
            }
            if (reader != null) {
                reader.close();
            }
            urlConnection.disconnect();
            String json = body.toString();
            logger.info("wx info:{}", json);
            return json;
        } catch (Exception e) {
            throw (ActivityUserException)e;
        }

    }
}
